package org.cc.cstc;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import org.cc.cstc.querystrategy.InsertEditorData;
import org.cc.cstc.utils.ClipBoardUtil;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public class PasteHandlerAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) return;
        //获取到当前激活的编辑器
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor == null) {
            Messages.showInfoMessage("No editor is currently active","Error");
            return;
        }

        Document document = editor.getDocument();
        CaretModel caretModel = editor.getCaretModel();
        Caret primaryCaret = caretModel.getPrimaryCaret();
        int offset = primaryCaret.getOffset();

        InsertEditorData insertEditorData = new InsertEditorData();
        List<String> data = insertEditorData.getPreInsertData();
        WriteCommandAction.runWriteCommandAction(project, () -> {
            int currentOffset = offset;
            for(String lineData : data){
                document.insertString(currentOffset, lineData + "\n");
                currentOffset += lineData.length() + 1;
            }
        });
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        /*
          只有当前打开了有效文件并且剪切板中存在文本类型的数据，菜单才会被激活
         */
        VirtualFile vf = e.getData(PlatformCoreDataKeys.VIRTUAL_FILE);
        e.getPresentation().setEnabled(vf != null && ClipBoardUtil.checkClipboardForText());
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.EDT;
    }
}
